<template>
  <view class="app-layout">
    <app-header :title="tit" />
    <view class="app-main">
      <view class="form-container">
        <view class="class-form">
          <scroll-view scroll-y="true" style="height: 100%;">
            <u-form labelPosition="left" labelWidth="90px" :model="formData" ref="refFrom">
              <view class="page-product-form-info">
                <u-form-item label="等级名称" required>
                  <uni-easyinput placeholder="请输入" clearable v-model="formData.levelName" :maxlength="10">
                    <template #right>
                      <text class="suffix-num">{{ (formData.levelName || '').length }}/10</text>
                    </template>
                  </uni-easyinput>
                </u-form-item>

                <view class="special-formitem">
                  <u-form-item label="等级卡片" required class="img2">
                    <uploadImage :max-count="1" :initial-images="initialImages" @upload-success="handleUpload"
                      @remove="handleRemove" />
                    <view style="color: #999999; font-size: 14px; margin-bottom: 4px">建议尺寸：710*300px，大小不超过3MB</view>
                  </u-form-item>
                </view>
                <u-form-item label="所需成长值" required>
                  <uni-easyinput placeholder="请输入数值" type="number" clearable v-model="formData.minPoints" :disabled ="type=='default'">
                    <template #right>
                      <text class="suffix-txt">分</text>
                    </template>
                  </uni-easyinput>
                </u-form-item>
                <u-form-item label="等级状态" required>
                  <u-switch v-model="formData.status" size="20" :activeValue="0" :inactiveValue="1"
                    activeColor="#20D048" :disabled ="type=='default'"></u-switch>
                </u-form-item>
                <u-form-item label="分类描述">
                  <u-textarea v-model="formData.benefits" :placeholder="'请输入'" :maxlength="200" :rows="5"
                    :autosize="true" count></u-textarea>

                </u-form-item>
              </view>
            </u-form>
          </scroll-view>
        </view>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref,
    computed
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    addLevel,
    updateLevel,
  } from '@/requests/apis/vip'
  import {
    uploadImgApi
  } from '@/requests/apis/user'
  import
  uploadImage
  from '@/components/upload-image/index.vue'
  let tit = ref('新增会员等级')
  let type = ref()
  let formData = ref({
    status: 0,
  })
  let fileList2 = ref([])
  let range = ref([])
  const initialImages = ref([]);
  onLoad((e) => {
    if (e.infoList) {
      console.log(e.type, 'type')
      type.value = e.type
      tit.value = '编辑会员等级'
      let data = JSON.parse(decodeURIComponent(e.infoList))
      console.log(data, '11111')
      formData.value.levelName = data.levelName
      formData.value.id = data.id
      formData.value.minPoints = data.minPoints + ''
      formData.value.status = data.status
      formData.value.benefits = data.benefits || ''
      if (data?.image) {
        initialImages.value[0] = data.image
      }
    }
  })
  // 处理上传成功事件
  const handleUpload = (imageUrl) => {
    console.log('图片上传成功，URL:', imageUrl);
    initialImages.value[0] = imageUrl
  };

  // 处理删除事件
  const handleRemove = (removedUrl) => {
    initialImages.value = []
  };



  const submit = () => {
    console.log(formData.value.isActive)
    const valid = [{
        k: 'levelName',
        err: '请输入等级名称',
      },
      {
        k: 'minPoints',
        err: '请输入所需成长值',
        validate: (value) => {
          const num = Number(value);
          return Number.isInteger(num) && num > 0;
        },
        validateErr: '所需成长值必须是大于0的正整数'
      },
    ]

    let err = ''
    if (!initialImages.value?.length) {
      err = '请上传等级卡片'
    }
    for (let item of valid) {
        if (item.k === 'minPoints' && type.value === 'default') {
          continue; // 直接进入下一个校验项
        }
      // 先校验非空
      if (!formData.value[item.k] && formData.value[item.k] !== 0) {
        err = item.err
        break
      }
      // 再校验数值合法性（如果有校验规则）
      if (item.validate && !item.validate(formData.value[item.k])) {
        err = item.validateErr
        break
      }
    }
    if (err) {
      uni.showToast({
        title: err,
        icon: 'none',
        duration: 2000,
      })
    } else {
      submitReq()
    }

  }
  const submitReq = async () => {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })

    let postData = JSON.parse(JSON.stringify(formData.value))
    postData.minPoints = Number(postData.minPoints)
    postData.image = initialImages.value
      .map((item) => {
        return item
      })
      .join(',')
    console.log(postData, 'postDatapostData')
    const fn = formData.value.id ? updateLevel : addLevel
    try {
      const res = await fn(postData)
      console.log(res, 'resres')

      if (res) {
        uni.showToast({
          title: res.Result || "",
          icon: 'success',
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 800)
      }
      uni.hideLoading()
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }
</script>
<style lang="scss" scoped>
  .form-container {
    width: 100%;
    background: #fff;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;

    .class-form {

      flex: 1;
      overflow: hidden;

      :deep(.u-form) {
        padding: 48px 280px;
        box-sizing: border-box;
      }

      .suffix-txt {
        background: #f5f6f8;
        border-left: 1px solid #e8ecef;
        font-weight: 400;
        font-size: 14px;
        color: #334681;
        padding: 6px 16px;
        box-sizing: border-box;
      }

      .suffix-num {
        font-weight: 400;
        font-size: 14px;
        color: rgba(51, 70, 129, 0.6);
        padding-right: 10px;
        box-sizing: border-box;
      }


    }
  }
</style>
